package com.pmcc.cj.service;

import com.pmcc.cj.entity.CjCommodity;
import com.pmcc.cj.repository.CjCommodityRepository;
import com.pmcc.utils.BeanUtils;
import com.pmcc.utils.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * Created by tomas on 2020/9/12.
 */
@Transactional
@Service
public class CjCommodityService {
    @Autowired
    CjCommodityRepository cjCommodityRepository;

    public ResultBean addCommodity(CjCommodity model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            model.setCreateTime(new Date());
            cjCommodityRepository.saveAndFlush(model);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean deleteCommodity(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            cjCommodityRepository.delete(id);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean modifyCommodity(Map map){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCommodity c = cjCommodityRepository.findOne(map.get("id").toString());
            BeanUtils.setBeanData(c, map);
            cjCommodityRepository.saveAndFlush(c);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean queryCommodity(){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            resultBean.setRows(cjCommodityRepository.findAll());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
